<?php

namespace Message\Controller;

use Common\Controller\BaseController;

//消息通知系统
class MessageController extends BaseController {

    public function _initialize() {
        parent::_initialize();
        if (empty($this->iUserId)) {
            $this->error("请登录!", -103);
        }
    }

    //消息列表
    public function messageList() {
        $iUserId = $this->iUserId;
        $page = I('page', 1, 'intval');
        $message_filter = I('message_filter', 0, 'intval');
        $page_size = 15;
        
        if(!empty($message_filter)){
            $arrWhere['is_read'] = 0;
        }
        $arrWhere['user_id'] = $iUserId;
        
        $messageCount = M('MessageUser')->where($arrWhere)->count();
        $messageList = M()->table('qy_message_user mu')->field('mu.message_id,message_title,push_time,mt.type_name as message_type_name,mu.is_read')
                ->join('qy_message as m USING(message_id)')
                ->join('qy_message_type as mt USING(message_type_id)')
                ->where($arrWhere)
                ->order('mu.id desc')
                ->page($page)
                ->limit($page_size)
                ->select();
        
        $this->returnList($messageList,$page,$page_size,$messageCount);
    }

    //消息详情
    public function detail() {
        $message_id = I('message_id', 0, 'intval');
        $iUserId = $this->iUserId;
        $messageInfo = M()->table('qy_message_user mu')->field('mu.message_id,message_title,push_time,message_img,content')
                ->join('qy_message as m USING(message_id)')
                ->where(array('mu.user_id' => $iUserId, 'mu.message_id' => $message_id))
                ->find();
        if (!empty($messageInfo)) {
            $messageInfo['message_img'] = !empty($messageInfo['message_img']) ? C('ADMIN_URL') . $messageInfo['message_img'] : '';
            $messageInfo['content'] = htmlspecialchars_decode($messageInfo['content']);
            //更新已读
            M('MessageUser')->where(array('message_id' => $message_id, 'user_id' => $iUserId))->save(array('is_read' => 1));
        }
        $this->returnList($messageInfo);
    }

    //全部标记已读
    public function readAll() {
        $iUserId = $this->iUserId;
        $res = M('MessageUser')->where(array('user_id' => $iUserId,'is_read'=>0))->save(array('is_read' => 1));
        $this->success('设置成功');
    }

    //消息未读总数
    public function noReadCount() {
        $iUserId = $this->iUserId;
        $readCount = M('MessageUser')->field('count(id) as no_read_count')->where(array('user_id' => $iUserId, 'is_read' => 0))->find();
        $this->returnList($readCount);
    }

}
